package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.LoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.RedisKeys;
import com.itheima.reggie.utils.SendSms;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @author mwj
 * @date 2021/11/27
 * @TIME:16:16
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpServletRequest request) {
        //1.生成一个验证码
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        //2.发送给指定的手机
        System.out.println("code是" + code);
        //SendSms.sendMsg(user.getPhone(), code + "");
        //3.把验证码存储到session中等待后续的验证码的校验
//        HttpSession session = request.getSession();
//        session.setAttribute(user.getPhone(), code);

        //4.REDIS优化缓存方案
        redisTemplate.opsForValue().set(RedisKeys.RG_CODE+user.getPhone(),code+"",5, TimeUnit.MINUTES);

        return R.success("发送验证码成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        //校验数据
        if (loginDto == null) {
            return R.error("参数异常");
        }
        //1). 获取前端传递的手机号和验证码
        HttpSession session = request.getSession();
        //2). 从Session中获取到手机号对应的正确的验证码
        //String code = (String) session.getAttribute(loginDto.getPhone());
        //从Redis中获取缓存的验证码
        String code = (String) redisTemplate.opsForValue().get(RedisKeys.RG_CODE + loginDto.getPhone());
        if (code == null || code.equals("")) {
            return R.error("请先获得验证码...");
        }
        //3). 进行验证码的比对 , 如果比对失败, 直接返回错误信息
        if (!code.equals(loginDto.getCode())) {
            return R.error("验证码不匹配");
        }
        //4). 如果比对成功, 需要根据手机号查询当前用户, 如果用户不存在, 则自动注册一个新用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, loginDto.getPhone());
        User user = userService.getOne(wrapper);
        if (user == null) { //代表用户不存在
            //注册一个用户
            user = new User();
            user.setPhone(loginDto.getPhone());
            //4.1 插入数据库中
            userService.save(user);
            //去掉return原因：因为注册后返回了，没有存储在session中
            //return R.success("登录成功");
        }
        //5). 将登录用户的ID存储Session中
        session.setAttribute("user", user.getId());
        //从Redis中删除缓存的验证码
        redisTemplate.delete(RedisKeys.RG_CODE + loginDto.getPhone());
        return R.success("登陆成功");

    }

    //移动端个人中心退出登录
    @PostMapping("/loginout")
    public R loginout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("user", null);
        return R.success("退出成功");
    }


}
